package org.zj.webview.app.listener;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Inject;
import org.zj.webview.app.config.HttpRandomAccessTokenConfig;
import org.zj.webview.app.config.WebViewConfig;
import org.noear.solon.annotation.Component;
import org.zj.webview.WebViewApi;
import org.zj.webview.app.filter.AppFilter;
import org.zj.webview.type.Slf4jLogger;
import org.zj.webview.type.WebWindow;
import org.zj.webview.type.WindowInfo;

/**
 * @author zj
 * @since 2025/7/25
 */
@Slf4j
@Component
public class WebViewStartedListener implements WebViewStateListener {

    @Inject
    private WebViewConfig config;

    @Inject
    private HttpRandomAccessTokenConfig httpRandomAccessTokenConfig;

    @Inject("${server.port}")
    private int serverPort;

    @Inject("${server.http.ssl.enable}")
    private boolean sslEnable;

    @Override
    public void onStarted() {
        LOGGER.info("WebView2 版本：{}", WebViewApi.getBrowserVersion());
        LOGGER.info("WebView2 兼容版本：{}", WebViewApi.getTargetCompatibleBrowserVersion());

        WebViewApi.setLogger(new Slf4jLogger());
        WindowInfo windowInfo = new WindowInfo();
        windowInfo.setTitle("测试");
        windowInfo.setX(100);
        windowInfo.setY(100);
        windowInfo.setWidth(800);
        windowInfo.setHeight(600);
        windowInfo.setFrameless(true);
        windowInfo.setResizable(true);
        WebWindow window = WebViewApi.createWindow(windowInfo);
        // 设置cookie，防止过滤器拦截
        window.addOrUpdateCookie(AppFilter.TOKEN_KEY,
                httpRandomAccessTokenConfig.getToken(),
                "127.0.0.1:" + serverPort, "/",
                true, sslEnable, -1.0D);
        window.loadUrl(String.format("http%s://127.0.0.1:%d/index.html", sslEnable ? "s" : "", serverPort));
    }
}
